import React, { Component } from 'react';
import _ from 'lodash';
import {
  StyleSheet, View, Text, TouchableOpacity, FlatList, Alert,
} from 'react-native';
import produce from 'immer';
import {
  ListFooter, BlankBackground, Loading, MyAccordion,
} from '../../../../components/index';
import * as todoService from '../../../../services/todo';
import MySearchBar from '../../../../components/searchbar';
import theme from '../../../../native-base-theme/variables';

export default class SearchSpareParts extends Component {
  static navigationOptions = {
    header: null,
  }

  page = 1; // 分页请求的当前页数

  startPosition = 0; // 开始滑动的位置

  index = 0; // 记录当前page的index

  searchValue = '';

  datas = [{ description: 'Inter酷睿I7', lubeType: '21', lubeModel: '11', datas: [{ name: '合金部配送站', num: '2' }, { name: '检修班配送站', num: '3' }] }];

  constructor(props) {
    super(props);
    this.state = {
      list: [{ id: '001', name: 'zs' }, { id: '002', name: 'zs1' }],
      refreshing: false,
      isMore: false,
      isError: false,
      showLoading: true,
    };
  }

  componentDidMount() {
    this._onInitRefresh();
  }

  fetchList = async (payload) => {
    try {
      this.setState({ isError: false });
      const currPage = this.page + 1;
      const { list, page, total } = await todoService.choiceSearch({ ...payload, page: currPage }, `${todoService.serverName}/device/fualt/queryMaintOrg`);

      this.setState(produce(draft => {
        // eslint-disable-next-line no-restricted-syntax
        draft.list.push(...list);
        this.page = page;
        draft.isMore = draft.list.length < total;
        draft.total = total;
      }));
    } catch (error) {
      this.setState({ isError: true });
    }
  }

  refreshList = async (payload) => {
    try {
      this.setState({ isError: false });
      const { list, page, total } = await todoService.choiceSearch({ ...payload, page: 1 }, `${todoService.serverName}/device/fualt/queryMaintOrg`);
      const isMore = list.length < total;
      this.setState(produce(draft => {
        // eslint-disable-next-line no-restricted-syntax
        draft.list = list;
        draft.refreshing = false;
        this.page = page;
        draft.isMore = isMore;
        draft.total = total;
      }));
    } catch (error) {
      this.setState({ isError: true, refreshing: false });
    }
  }

  initRefreshList = async (payload) => {
    try {
      this.setState({ showLoading: true, isError: false, list: [] });
      const { list, page, total } = await todoService.choiceSearch({ ...payload, page: 1 }, `${todoService.serverName}/device/fualt/queryMaintOrg`);
      const isMore = list.length < total;
      this.setState(produce(draft => {
        draft.list = list;
        draft.showLoading = false;
        this.page = page;
        draft.isMore = isMore;
        draft.total = total;
      }));
    } catch (error) {
      this.setState({ isError: true, showLoading: false });
    }
  }

  // 刷新时候获取数据
  _onRefresh = () => {
    this.refreshList({ condition: this.searchValue });
  }

  // 初始化的时候获取数据
  _onInitRefresh = () => {
    this.initRefreshList({ condition: this.searchValue });
  }

  // 上拉加载数据
  _onEndReached = () => {
    if (this.state.isMore) {
      this.fetchList({ condition: this.searchValue });
    }
  }

  // 跳转到库存详情页面
  toDetail = (sparePart, repertory) => {
    // const { datas } = this.props.navigation.state.params;
    this.props.navigation.goBack();
    this.props.navigation.navigate({
      routeName: 'SparePartsInventoryDetail',
      params: {
        sparePart,
        repertory,
      },
    });
  }

  // 列表的item组件
  _renderItem = (item) => (
    <View
      style={{ flex: 1 }}
    >
      <MyAccordion datas={this.datas} toDetail={this.toDetail} />
    </View>
  );

  // 列表的分割线
  _renderItemSeparator = () => (
    <View style={{ height: 1, backgroundColor: '#EDF5FA' }} />
  )

  // 列表上拉加载的组件
  _renderListFooter = () => (
    (this.state.list.length > 0) && <ListFooter isMore={this.state.isMore} />
  );

  _onSearch = async (searchValue) => {
    this.searchValue = searchValue;
    this.initRefreshList({ condition: this.searchValue });
  }

  // choiceConfirm = () => {
  //   const list = this.state.list.filter((it) => (it.checked));
  //   if (list && list.length > 0) {
  //     this.props.choiceConfirm(list);
  //     this.props.onClose();
  //   } else {
  //     // alert('请至少选择一个');
  //     Alert.alert(
  //       '提示',
  //       '请至少选择一个！',
  //       [
  //         { text: '取消', style: 'cancel' },
  //         {
  //           text: '确定',
  //         },
  //       ],
  //     );
  //   }
  // };

  onClose = () => {
    this.props.navigation.goBack();
  }

  render() {
    const {
      showLoading, isError, list, refreshing,
    } = this.state;

    let mView = <Loading />;
    if (!showLoading) {
      if (list.length === 0) {
        mView = <BlankBackground isError={isError} onRefresh={this._onInitRefresh} />;
      } else {
        mView = (
          <FlatList
            renderItem={this._renderItem}
            data={list}
            keyExtractor={(item, index) => item + index}
            onRefresh={this._onRefresh}
            refreshing={refreshing}
            onEndReachedThreshold={0.05}
            onEndReached={this._onEndReached}
            ListFooterComponent={this._renderListFooter}
          />
        );
      }
    }

    const header = (
      <View>
        <MySearchBar placeholder="请输入备件名称" cancel={this.onClose} search={this._onSearch} />
      </View>
    );

    return (
      <View
        style={styles.conteniner}
      >
        {header}
        <View style={{ flex: 1, backgroundColor: theme.myPrimary }}>
          {mView}
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  conteniner: {
    flex: 1,
  },
  record_text: {
    paddingLeft: 10,
    paddingBottom: 10,
    fontSize: 12,
  },
  record_text_container: {
    padding: 10,
    flex: 1,
  },
  record_text_bg: {
    padding: 12,
    borderTopWidth: 1,
    borderTopColor: '#DEE1E6',
    backgroundColor: '#fff',
  },
  clear_text_bg: {
    padding: 12,
    borderTopWidth: 1,
    borderTopColor: '#DEE1E6',
    textAlign: 'center',
    fontSize: 12,
  },
  footer: {
    width: '100%',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: theme.myPrimary,
    height: 48,
    borderTopWidth: 0.5,
    borderTopColor: 'rgba(255,255,255,0.5)',
  },
});
